# Addition
2 + 3
[1] 5
Welcome to the preliminary basics tutorial for R! In this tutorial, we’ll cover some fundamental concepts and operations in the R programming language. Once you have R and RStudio installed, open RStudio and follow along with the following basics.
The RStudio interface consists of several panels, including the console, script editor, environment, and more. The console is where you can directly interact with R by typing commands and executing them.
Let’s start with some basic arithmetic operations:
You can assign values to variables using the assignment operator <-
:
R supports several data structures, including vectors, matrices, data frames, and lists.
Vectors are the simplest type of data structure in R. They contain items of the same type (numeric, character, or logical). You can create a vector using the c()
function.
[1] 1 2 3 4 5
[1] "apple" "banana" "cherry"
[1] TRUE FALSE TRUE
You can access vector elements using square brackets []
.
Matrices are two-dimensional data structures where every element has the same type. You can create a matrix using the matrix()
function.
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
You can access matrix elements using square brackets [,]
.
Data frames are used to store tabular data. They are similar to matrices but can contain different types of data in each column. You can create a data frame using the data.frame()
function.
# Create a data frame
my_data_frame <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(24, 30, 28),
Salary = c(50000, 60000, 55000)
)
my_data_frame
Name Age Salary
1 Alice 24 50000
2 Bob 30 60000
3 Charlie 28 55000
You can access data frame elements using $
for columns or [,]
for specific elements.
Lists are R’s most complex data structure. They can contain elements of different types, including numbers, strings, vectors, and even other lists. You can create a list using the list()
function.
# Create a list
my_list <- list(
Name = "Alice",
Age = 24,
Hobbies = c("Reading", "Cycling", "Hiking")
)
my_list
$Name
[1] "Alice"
$Age
[1] 24
$Hobbies
[1] "Reading" "Cycling" "Hiking"
You can access list elements using $
or [[ ]]
.
R provides numerous built-in functions for performing various tasks. Let’s use the mean()
function as a very simple example to calculate the mean of the numeric vector we created previously:
In this tutorial, we’ve covered some preliminary basics of R, including arithmetic operations, variable assignment, data structures, and functions. These concepts provide a foundation for further exploration of R programming.
For more in-depth learning, consider exploring additional resources such as online tutorials, books, and documentation.
Happy coding with R!